package com.tencent.iov.cowin.befsale.clue.service.cus.impl;

import com.google.common.collect.Lists;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.QueryCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.UpdateClueEmpRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.UpdateCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerFollowPlanResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerFollowRecordResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.Clue;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueFail;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomerFollowRecord;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomerFollowRecord;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.CustomerBehaviorStatistical;
import com.tencent.iov.cowin.befsale.clue.repository.tenant.TenantManager;
import com.tencent.iov.cowin.befsale.clue.service.cus.CustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowPlanService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.value.enums.CustomerTypeEnum;
import com.tencent.iov.cowin.befsale.clue.value.utils.CustomerUtil;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.common.enums.DeleteEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author xiamu
 * @Date 2022/1/14 22:57
 * @Version 1.0
 **/
@Service
@Slf4j
public class CustomerFollowRecordServiceImpl implements CustomerFollowRecordService {

    @Autowired
    private OemCustomerFollowRecordService oemCustomerFollowRecordService;
    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;
    @Autowired
    private TenantManager tenantManager;
    @Autowired
    private OemCustomerFollowPlanService oemCustomerFollowPlanService;

    @Override
    public CustomerFollowRecordResponse getDetailById(Long id) {
        CustomerFollowRecordResponse customerFollowRecordResponse;
        if (CustomerUtil.isDealer()) {
            DealerCustomerFollowRecord dealerCustomerFollowRecord = dealerCustomerFollowRecordService.getDetailById(id);
            customerFollowRecordResponse = EmptyUtils.isNotEmpty(dealerCustomerFollowRecord) ?
                    BeanUtil.copy(dealerCustomerFollowRecord, CustomerFollowRecordResponse.class) : null;
            return customerFollowRecordResponse;
        }
        OemCustomerFollowRecord oemCustomerFollowRecord = oemCustomerFollowRecordService.getDetailById(id);
        customerFollowRecordResponse = EmptyUtils.isNotEmpty(oemCustomerFollowRecord) ?
                BeanUtil.copy(oemCustomerFollowRecord, CustomerFollowRecordResponse.class) : null;
        return customerFollowRecordResponse;
    }

    @Override
    public Long insert(AddCustomerFollowRecordRequest request) {
        //填充跟进记录状态与二级状态
        DealerCustomerFollowRecordAssembler.fillCustomerFollowRecordStatus(request);
        if (CustomerUtil.isDealer()) {
            return dealerCustomerFollowRecordService.insert(request);
        }
        return oemCustomerFollowRecordService.insert(request);
    }

    @Override
    public int insertBatch(List<AddCustomerFollowRecordRequest> requests) {
        if (CustomerUtil.isDealer()) {
            return dealerCustomerFollowRecordService.insertBatch(requests);
        }
        return oemCustomerFollowRecordService.insertBatch(requests);
    }

    @Override
    public int update(UpdateCustomerFollowRecordRequest request) {
        if (CustomerUtil.isDealer()) {
            DealerCustomerFollowRecord dealerFollowRecord = BeanUtil.copy(request, DealerCustomerFollowRecord.class);
            return dealerCustomerFollowRecordService.update(dealerFollowRecord);
        }
        OemCustomerFollowRecord oemFollowRecord = BeanUtil.copy(request, OemCustomerFollowRecord.class);
        return oemCustomerFollowRecordService.update(oemFollowRecord);
    }

    @Override
    public List<CustomerFollowRecordResponse> getListByParam(QueryCustomerFollowRecordRequest request) {
        request.setDeleted(DeleteEnum.INIT.getFlag());
        OrderField recordOrderField = new OrderField("id", "DESC");
        request.setOrderFields(Lists.newArrayList(recordOrderField));
        List<CustomerFollowRecordResponse> recordList;
        //只获取经销商跟进信息
        if (CustomerUtil.isDealer()) {
            recordList =  dealerCustomerFollowRecordService.getListByParam(request);
        } else {

            //总部+经销商客户信息
            OemCustomerFollowRecord followRecordRequest = BeanUtil.copy(request, OemCustomerFollowRecord.class);
            List<CustomerFollowRecordResponse> oemFollowRecords = oemCustomerFollowRecordService.getListByParam(followRecordRequest);
            if (EmptyUtils.isEmpty(oemFollowRecords)) {
                oemFollowRecords = Lists.newArrayList();
            }
            oemFollowRecords.stream().forEach(oemR->{
                if(oemR.getNextFollowPlanId()!=null){
                    oemR.setNextPlanRes(oemCustomerFollowPlanService.getDetailById(oemR.getNextFollowPlanId()));
                }
            });

            //获取经销商信息后
            List<CustomerFollowRecordResponse> dealerFollowRecords = dealerCustomerFollowRecordService.getListByParam(request);
            if (EmptyUtils.isEmpty(dealerFollowRecords)) {
                return oemFollowRecords;
            }
            oemFollowRecords.addAll(dealerFollowRecords);
            //排序后返回
            recordList = oemFollowRecords.stream().sorted(Comparator.comparing(CustomerFollowRecordResponse::getCreatedTime).reversed()).collect(Collectors.toList());
        }
        if (EmptyUtils.isEmpty(recordList)) {
            return null;
        }
        Map<String, String> dicMap = tenantManager.getDicMapGroupByCode(new QueryDictionariesRequest());
        recordList.forEach(record -> DealerCustomerFollowRecordAssembler.fillFollowDetailStr(record, dicMap));
        return recordList;
    }

    @Override
    public CustomerFollowRecordResponse getOneByParam(QueryCustomerFollowRecordRequest request) {
        if (CustomerUtil.isDealer()) {
            DealerCustomerFollowRecord dealerFollowRecord = BeanUtil.copy(request, DealerCustomerFollowRecord.class);
            return dealerCustomerFollowRecordService.getOneByParam(dealerFollowRecord);
        }
        OemCustomerFollowRecord oemFollowRecord = BeanUtil.copy(request, OemCustomerFollowRecord.class);
        return oemCustomerFollowRecordService.getOneByParam(oemFollowRecord);
    }

    @Override
    public List<CustomerBehaviorStatistical> statisticalByStatus(Date startDate, Date endDate, List<Integer> statues, Integer cusType) {
       if (CustomerTypeEnum.isDealer(cusType)) {
           return dealerCustomerFollowRecordService.statisticalByStatus(startDate, endDate, statues);
       }
       return oemCustomerFollowRecordService.statisticalByStatus(startDate, endDate, statues);
    }

    @Override
    public List<CustomerBehaviorStatistical> statisticalBySecondStatus(Date startDate, Date endDate, List<Integer> secondStatues, Integer cusType) {
        if (CustomerTypeEnum.isDealer(cusType)) {
            return dealerCustomerFollowRecordService.statisticalBySecondStatus(startDate, endDate, secondStatues);
        }
        return oemCustomerFollowRecordService.statisticalBySecondStatus(startDate, endDate, secondStatues);
    }

    @Override
    public int insertBatchByDistribute(List<Clue> clues, UpdateClueEmpRequest request, Map<Long, CustomerResponse> customerMap) {
        List<AddCustomerFollowRecordRequest> addFollowRecordRequests = Lists.newArrayList();
        clues.forEach(clue -> {
            AddCustomerFollowRecordRequest addFollowRecordRequest = DealerCustomerFollowRecordAssembler
                    .initAddByDistribute(clue, request, customerMap.get(clue.getCusId()));
            dealerCustomerFollowRecordService.fillExpireInfoAndUpdateFollowPlan(addFollowRecordRequest);
            addFollowRecordRequests.add(addFollowRecordRequest);
        });
        if (CustomerUtil.isDealer()) {
            int recordResult = dealerCustomerFollowRecordService.insertBatch(addFollowRecordRequests);
            if (recordResult<= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "分配顾问-批量保存跟进记录失败");
            }
            return recordResult;
        }
        throw new BusinessException(NEError.BUSINESS_ERROR, "总部暂不支持非配顾问");
    }

    @Override
    public Long insertByFailClue(Clue clue, UpdateClueEmpRequest request, CustomerResponse customerResponse, ClueFail clueFail) {
        AddCustomerFollowRecordRequest followRecordRequest = DealerCustomerFollowRecordAssembler.initAddByFailClue(clue, request, clueFail, customerResponse);
       return this.insert(followRecordRequest);
    }
}
